<?php

namespace App\Console\Commands\Mybank;

use App\Kuafu\Mybank\Service\MybankService;
use App\Kuafu\Order\Model\OrderCouponSplitModel;
use App\Kuafu\Order\Model\OrderDetailSplitModel;
use App\Kuafu\Order\Model\OrderDiscountSplitModel;
use App\Kuafu\Order\Model\OrderExternalSplitModel;
use App\Kuafu\Order\Model\OrderPayUnionSplitModel;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\WaiMai\Model\WaiMaiOrderDetailModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderIdShopIdMappingModel;
use App\Kuafu\WaiMai\Model\WaiMaiOrderModel;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SyncQaOrderCommand extends Command
{
    protected $signature = 'mybank:SyncQaOrder';

    protected $description = '同步生产订单[堂食, 外卖]到测试环境';

    protected $startAt = '';
    protected $endAt   = '';

    public function handle()
    {
        // 检查本地数据
        return false;
        if (!(config('app.env') == 'dev' || config('app.env') == 'qa')) {
            return false;
        }

        $this->startAt = strtotime(date('Y-m-d', strtotime('-3 day')) . '00:00:00');
        $this->endAt   = strtotime(date('Y-m-d', strtotime('-1 day')) . '23:59:59');

        $shopIds = [
            13154,
            12018,
            13687
        ];

        $this->info('同步 生产 至 QA 数据库...开始');

        $this->setProdDb();

        foreach ($shopIds as $shopId) {
            /**** 同步外卖数据 ****/
            $this->syncWmOrder($shopId);

            /**** 同步堂食订单 ****/
            $this->syncOrder($shopId);
        }


        $this->info('完成');
    }

    private function syncOrder($shopId)
    {
        $tableNum = str_pad((int)$shopId % 100, 3, 0, 0);

        $tableName = 'kf_order_' . $tableNum;

        $orderList = DB::connection('rms-prod-rms')
                       ->table($tableName)
                       ->where('shopId', $shopId)
                       ->whereBetween('completeTime', [$this->startAt, $this->endAt])
                       ->get()
                       ->map(function ($value) {
                           return (array)$value;
                       })
                       ->toArray();

        if (empty($orderList)) {
            return;
        }
        $orderIds = array_column($orderList, 'orderId');

        OrderSplitModel::suffix($shopId)
                       ->query()
                       ->whereIn('orderId', $orderIds)
                       ->delete();


        foreach ($orderList as &$orderItem) {
            $orderItem['brokeragePer'] = '0.01%';
            $orderItem['brokerage']    = '1';
        }

        OrderSplitModel::suffix($shopId)
                       ->query()
                       ->insert($orderList);


        $tableList = [
            'order_detail'   => OrderDetailSplitModel::class,
            'order_coupon'   => OrderCouponSplitModel::class,
            'order_discount' => OrderDiscountSplitModel::class,
        ];

        foreach ($tableList as $table => $model) {
            $tableName = 'kf_' . $table . '_' . $tableNum;
            $orderList = DB::connection('rms-prod-rms')
                           ->table($tableName)
                           ->whereIn('orderId', $orderIds)
                           ->where('isDeleted', 0)
                           ->get()
                           ->map(function ($value) {
                               return (array)$value;
                           })
                           ->toArray();

            $model::suffix($shopId)
                  ->query()
                  ->whereIn('orderId', $orderIds)
                  ->delete();

            $model::suffix($shopId)
                  ->query()
                  ->insert($orderList);

//            $this->info($shopId . ' ' . $table . '同步中...');
        }

        // 同步 pay stream
        $tableName = 'kf_pay_stream_' . $tableNum;
        $orderList = DB::connection('rms-prod-rms')
                       ->table($tableName)
                       ->whereIn('orderId', $orderIds)
                       ->get()
                       ->map(function ($value) {
                           return (array)$value;
                       })
                       ->toArray();
        $tableName = 'pay_stream_' . $tableNum;
        DB::connection('mysqlOrder')
          ->table($tableName)
          ->whereIn('orderId', $orderIds)
          ->delete();

        DB::connection('mysqlOrder')
          ->table($tableName)
          ->insert($orderList);

        return;
    }

    private function syncWmOrder($shopId)
    {
        $tableNum        = str_pad((int)$shopId % 100, 3, 0, 0);
        $tableName       = 'kf_waimai_orders_' . $tableNum;
        $detailTableName = 'kf_waimai_order_details_' . $tableNum;
        $orderList       = DB::connection('rms-prod-wm')
                             ->table($tableName)
                             ->where('shopId', $shopId)
                             ->whereBetween('completeTime', [$this->startAt, $this->endAt])
                             ->get()
                             ->map(function ($value) {
                                 return (array)$value;
                             })
                             ->toArray();

        if (empty($orderList)) {
            return;
        }

        $orderIds = array_column($orderList, 'orderId');


        foreach ($orderList as &$value) {
            $value['brokeragePer'] = '0.01%';
            $value['brokerage']    = '1';
        }
        // 同步 order 表数据
        WaiMaiOrderModel::suffix($shopId)
                        ->whereIn('orderId', $orderIds)
                        ->delete();

        WaiMaiOrderModel::suffix($shopId)
                        ->insert($orderList);


        // 同步 order_detail 表
        $orderDetailList = DB::connection('rms-prod-wm')
                             ->table($detailTableName)
                             ->where('shopId', $shopId)
                             ->whereIn('orderId', $orderIds)
                             ->get()
                             ->map(function ($value) {
                                 return (array)$value;
                             })
                             ->toArray();

        WaiMaiOrderDetailModel::suffix($shopId)
                              ->whereIn('orderId', $orderIds)
                              ->delete();

        WaiMaiOrderDetailModel::suffix($shopId)
                              ->insert($orderDetailList);


        // 同步 waimai_all
        $orderShopIdMap = DB::connection('rms-prod-wm-all')
                            ->table('kf_waimai_order_id_shop_id_mappings')
                            ->where('shopId', $shopId)
                            ->whereIn('orderId', $orderIds)
                            ->get()
                            ->map(function ($value) {
                                return (array)$value;
                            })
                            ->toArray();

        WaiMaiOrderIdShopIdMappingModel::query()
                                       ->whereIn('orderId', $orderIds)
                                       ->delete();

        WaiMaiOrderIdShopIdMappingModel::query()
                                       ->insert($orderShopIdMap);
    }

    private function setProdDb()
    {
        Config::set('database.connections.rms-prod-rms', [
            'driver'         => 'mysql',
            'url'            => '',
            'host'           => 'rm-bp1981egtkilp75bcso.mysql.rds.aliyuncs.com',
            'database'       => 'kf_rms_order_1',
            'username'       => 'user_xm',
            'password'       => 'd7fb!sGod!',
            'port'           => '3306',
            'unix_socket'    => '',
            'charset'        => 'utf8mb4',
            'collation'      => 'utf8mb4_general_ci',
            'prefix'         => '',
            'prefix_indexes' => true,
            'strict'         => false,
            'engine'         => null,
            'options'        => extension_loaded('pdo_mysql') ? array_filter([
                \PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]);
        Config::set('database.connections.rms-prod-wm', [
            'driver'         => 'mysql',
            'url'            => '',
            'host'           => 'rm-bp1981egtkilp75bcso.mysql.rds.aliyuncs.com',
            'database'       => 'kf_waimai_order_1',
            'username'       => 'user_xm',
            'password'       => 'd7fb!sGod!',
            'port'           => '3306',
            'unix_socket'    => '',
            'charset'        => 'utf8mb4',
            'collation'      => 'utf8mb4_general_ci',
            'prefix'         => '',
            'prefix_indexes' => true,
            'strict'         => false,
            'engine'         => null,
            'options'        => extension_loaded('pdo_mysql') ? array_filter([
                \PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]);
        Config::set('database.connections.rms-prod-wm-all', [
            'driver'         => 'mysql',
            'url'            => '',
            'host'           => 'rm-bp1981egtkilp75bcso.mysql.rds.aliyuncs.com',
            'database'       => 'kf_waimai_order_all',
            'username'       => 'user_xm',
            'password'       => 'd7fb!sGod!',
            'port'           => '3306',
            'unix_socket'    => '',
            'charset'        => 'utf8mb4',
            'collation'      => 'utf8mb4_general_ci',
            'prefix'         => '',
            'prefix_indexes' => true,
            'strict'         => false,
            'engine'         => null,
            'options'        => extension_loaded('pdo_mysql') ? array_filter([
                \PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]) : [],
        ]);
    }
}
